// pages/statistics/index/index.js
import Toast from '../../../vant/toast/toast'
import {
  getOrderList,
  orderRefund,
  getOrderListV2
} from '../../../utils/api/index.js'
import moment from '../../../utils/moment.js'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    isLogin: true,
    refundStatusStr: {
      'CANCEL': '确认收货',
      'REFUNDED': '退款成功',
      'REFUSED': '退款失败'
    },
    orderStatusStr: {
      'CANCEL': '已取消',
      'REFUSED': '系统拒绝',
      'INCOMPLETE': '待完善',
      'UNPAY': '未支付',
      'PAID': '待打单',
      'PRINTED': '待揽收',
      'SHIPPED': '待收货',
      'DELIVERING': '待收货',
      'RECEIVED': '已完成'
    },
    minValue: '',
    maxValue: '',
    transValue: 0,
    wrapperStyle: '',
    downFlag: true,
    orderStatus: '',
    pageNo: 1,
    pageSize: 10,
    orderDate: '',
    totalNum: 0,
    dataList: [],
    isAll: false,
    refundPopupShow: false,
    refundOperation: '',
    refundOrderId: '',
    keyword: '',
    noPash: false,
    loading: false,
    orderType: "REGULAR",//1、REGULAR：常规订单（包含REGULAR以及BATCH）；2、FRUIT：水果订单。默认值为REGULAR



    trackingNoNum: 1,//1是一个包裹,2是多个报错
    trackingNoData: [],//处理过的多个数据 是个数组

    orderId: "",
    // orderType:"",
    isShowRefund: false,
    isShowCancel: false,
    refundOperation: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options);

    this.setData({
      orderType: options.orderType,
    })

    wx.getSystemInfo({
      success: function (res) {
        const windowHeight = res.windowHeight
        let minValue = windowHeight * 0.25
        let maxValue = windowHeight * 0.75
        this.setData({
          minValue,
          maxValue
        })
      }.bind(this),
    })
    const date = new Date()
    const year = date.getFullYear()
    const month = date.getMonth() + 1 < 10 ? `0${date.getMonth() + 1}` : date.getMonth() + 1
    const day = date.getDate() < 10 ? `0${date.getDate()}` : date.getDate()
    this.setData({
      orderDate: `${year}-${month}-${day}`
    })


  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    // 获取日期选择器
    this.datepicker = this.selectComponent('#datepicker');
    // this.getOrders()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

    this.setData({
      isLogin: true,
      orderStatus: '',
      pageNo: 1,
      totalNum: 0,
      dataList: [],
      isAll: false
    })
    if (this.data.keyword && this.data.orderType) {
      this.getOrders()

    }
    const loginInfo = wx.getStorageSync('loginInfo')
    if (loginInfo) {
      if (this.data.noPash) {
        this.setData({
          noPash: false
        })
        return;
      }
      this.setData({
        isLogin: true,
        orderStatus: '',
        pageNo: 1,
        totalNum: 0,
        dataList: [],
        isAll: false
      })
      // this.getOrders()
      this.datepicker = this.selectComponent('#datepicker');
    } else {
      this.setData({
        isLogin: false
      })
    }
    this.setData({
      dataList: []
    })
    // setTimeout(() => {
    //   console.log('定时器');

    // },1500)

    // this.toGetData()

  },
  toLogin() {
    wx.navigateTo({
      url: '/pages/mine/login/index',
    })
  },

  touchStart(e) {
    this.data.startY = e.changedTouches[0].clientY
  },
  touchEnd(e) {
    const endY = e.changedTouches[0].clientY
    const startY = this.data.startY
    const diff = endY - startY
    const absDiff = diff > 0 ? diff : -diff
    const middleValue = this.data.maxValue - this.data.minValue

    if (diff > 0) {
      // 向下滑动
      this.toMove(this.data.maxValue - this.data.minValue)
      this.datepicker.mulLine()
    } else if (diff < 0) {
      this.toMove(0)
      this.datepicker.singleLine()
    }
  },

  touchMove(e) {
    let timer = null
    if (!timer) {
      timer = setTimeout(() => {
        const clientY = e.changedTouches[0].clientY
        if (clientY > this.data.minValue && clientY < this.data.maxValue) {

        }
        clearTimeout(timer)
      }, 1000)
    }
  },
  // 移动
  toMove(value) {
    const transform = `translate3d(0,${value}px, 0)`;
    const transition =
      'transform .6s cubic-bezier(0.18, 0.89, 0.32, 1)';
    this.setData({
      wrapperStyle: `
        -webkit-transform: ${transform};
        -webkit-transition: ${transition};
        transform: ${transform};
        transition: ${transition};
      `
    });
  },

  statusChange(e) {
    const status = e.target.dataset.type
    this.setData({
      orderStatus: status,
      isAll: false,
      pageNo: 1,
      totalNum: 0,
      dataList: []
    })
    this.getOrders()
  },

  // 获取订单列表
  getOrders() {
    wx.showLoading({
      title: '加载中...',
      mask: true
    })
    getOrderListV2({
      // orderDate: this.data.orderDate,
      orderStatus: this.data.orderStatus,
      pageNo: this.data.pageNo,
      pageSize: this.data.pageSize,
      keyword: this.data.keyword,
      orderType: this.data.orderType
    }).then(res => {
      if (res.resultStatus) {
        if (res.resultData.dataList.length == 0 && this.data.pageNo > 1) {
          Toast('没有更多了')
        }
        if (res.resultData.dataList.length) {
          const resultList = res.resultData.dataList
          // resultList.forEach(f => {
          //   f.createTime = moment(f.createTime).format('MM-DD HH:mm')
          // })
          let dataList = []
          if (this.data.pageNo > 1) {
            dataList = this.data.dataList.concat(resultList)
          } else {
            dataList = resultList
          }
          // const dataList = this.data.dataList.concat(resultList)
          // this.setData({
          //   totalNum: res.resultData.totalNum,
          //   dataList,
          // })



          let arrNew = dataList.map((item) => {
            return {
              ...item,
              trackingNo: (item.trackingNo !== null) && (!Array.isArray(item.trackingNo)) ? item.trackingNo.split(';') : item.trackingNo,
              trackingNoNum: item.trackingNo !== null && item.trackingNo.indexOf(";") != -1 ? 2 : 1,
            }
          })


          this.setData({
            totalNum: res.resultData.totalNum,
            dataList: arrNew
          })












        } else {
          this.setData({
            isAll: true
          })
        }
      } else {
        Toast(res.errorMessage)
      }
      wx.hideLoading();
    }).catch(err => {
      wx.hideLoading();
    })
  },

  // 搜索
  toSearch(e) {
    const keyword1 = e.detail == null ? '' : e.detail;
    const keyword = keyword1.trim();
    this.setData({
      keyword,
      orderStatus: '',
      dataList: [],
      pageNo: 1,
      orderType: this.data.orderType,
    })
    this.getOrders();
  },

  // 查看详情
  toDetail(e) {

    const orderId = e.detail
    wx: wx.navigateTo({
      url: '/pages/statistics/order/index?orderId=' + orderId,
      success: () => {
        this.setData({
          noPash: true
        })
      }
    })
  },

  // 申请/取消退款
  // toRefund(e) {
  //   const orderId = e.detail.orderid
  //   const refundStatus = e.detail.refundstatus
  //   if (!refundStatus || refundStatus === 'CANCEL') {
  //     // 申请
  //     this.setData({
  //       refundPopupShow: true,
  //       refundOperation: 'REFUND',
  //       refundOrderId: orderId
  //     })

  //   } else {
  //     // 取消
  //     this.setData({
  //       refundPopupShow: true,
  //       refundOperation: 'CANCEL',
  //       refundOrderId: orderId
  //     })
  //   }
  // },

  //申请/取消退款
  toRefund(e) {
    console.log(e);
    const orderType = e.currentTarget.dataset.type
    const orderId = e.currentTarget.dataset.orderid


    if (orderType == "CANCEL") {
      this.setData({
        refundOrderId: orderId,
        isShowCancel: true,
        refundOperation: "CANCEL",
      })
    } else {
      this.setData({
        refundOrderId: orderId,
        isShowRefund: true,
        refundOperation: "REFUND",
      })

    }


  },


  //取消
  onClose() {
    this.setData({
      isShowRefund: false
    });
  },

  // 确定
  onSubmit() {
    orderRefund({
      orderId: this.data.refundOrderId,
      refundOperation: this.data.refundOperation,
    }).then(res => {
      if (res.resultStatus) {
        Toast(this.data.refundOperation === 'CANCEL' ? '取消退款成功' : '申请退款成功');


        let a = this.data.dataList
        a.map((item, index) => {
          if (item.orderId == this.data.refundOrderId)
            item.refundStatus = 'PENDING'
        })
        this.setData({
          isShowRefund: false,
          dataList: a

        });
        // this.getOrders()  //用上面的方法 解决 分页之后按钮没有更新的问题
      } else {
        Toast(res.errorMessage);
      }
    })
  },

  //取消
  onClose1() {
    this.setData({
      isShowCancel: false
    });
  },

  // 确定
  onSubmit1() {
    orderRefund({
      orderId: this.data.refundOrderId,
      refundOperation: this.data.refundOperation,
    }).then(res => {
      if (res.resultStatus) {
        Toast(this.data.refundOperation === 'CANCEL' ? '取消退款成功' : '申请退款成功');
        this.setData({
          isShowCancel: false
        });

        let b=this.data.dataList
        b.map((item,index)=>{
          if(item.orderId==this.data.refundOrderId)
          item.refundStatus=null
        })
        this.setData({
          isShowRefund: false,
          dataList:b
        });




        // this.getOrders()

      } else {
        Toast(res.errorMessage);
      }
    })
  },
  // 查看详情
  handleInfo(e) {
    wx.setStorageSync('nowOrderstatus', e.currentTarget.dataset.item.complainExistStatus)
    const orderId = e.currentTarget.dataset.item.orderId
    wx.navigateTo({
      url: '/pages/statistics/order/index?orderId=' + orderId,
    })
  },
  goPage(e) {
    wx.navigateTo({
      url: '/pages/statistics/complaint/index?orderId=' + e.currentTarget.dataset.item.orderId + '&orderNo=' + e.currentTarget.dataset.item.orderNo
    });
  },
  handleAction(data) {
    if (data.detail === 'ok' && this.data.refundOrderId && this.data.refundOperation) {
      this.setData({
        refundPopupShow: false
      })
      orderRefund({
        orderId: this.data.refundOrderId,
        refundOperation: this.data.refundOperation
      }).then(res => {
        if (res.resultStatus) {
          Toast(this.data.refundOperation === 'CANCEL' ? '取消退款成功' : '申请退款成功')
          const dataList = this.data.dataList.map(f => {
            if (f.orderId === this.data.refundOrderId) {
              f.refundStatus = this.data.refundOperation === 'CANCEL' ? 'CANCEL' : 'PENDING'
            }
            return f
          })
          this.setData({
            dataList,
            refundOperation: '',
            refundOrderId: ''
          })
        } else {
          Toast(res.errorMessage)
        }
      })
    } else {
      this.setData({
        refundPopupShow: false,
        refundOperation: '',
        refundOrderId: ''
      })
    }
  },

  bindscrolltolower() {
    if (!this.data.isAll) {
      this.setData({
        pageNo: this.data.pageNo + 1
      })
      this.getOrders()
    }
  },


  toLogisticsOrder() {
    this.setData({
      orderType: 'REGULAR',
    })
    this.setData({
      orderType: 'REGULAR',
      isAll: false,
      pageNo: 1,
      totalNum: 0,
      dataList: []
    })
    this.getOrders()
  },

  toFruitOrder() {
    this.setData({
      orderType: 'FRUIT',
      isAll: false,
      pageNo: 1,
      totalNum: 0,
      dataList: []
    })
    this.getOrders()
  },
  // 返回上一页
  onCancel() {
    wx.navigateBack({
      delta: 1,
    })
  },
  copy(e) {
    console.log(e);
    const data = e.currentTarget.dataset.text || ''
    wx.setClipboardData({ data: data })
  },







})